package development.bussiness;

import state.AlertListener;
import state.GameAlert;
import state.GameImage;
import state.socket.DataPackage;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.AvatarCache;
import development.FrmChooseAvatar;
import development.FrmUserInfo;
import development.Global;

public class AvatarBussiness implements AlertListener {
  public void onReceiveAvatar(DataPackage dataPackage) {
    String avatarId = dataPackage.nextString();
    ByteArray data = dataPackage.nextByteArray();
    AvatarCache.putAvatar(avatarId, GameImage.createImage(data, 0, data.len()));
  }
  
  public void onReceivedAvatarListByCategory(DataPackage dataPackage) {
    FrmChooseAvatar frmChooseAvatar = (FrmChooseAvatar) FrmChooseAvatar.instance();
    String category = dataPackage.nextString();
    if (category.equals(frmChooseAvatar.categories.array[frmChooseAvatar.categoryChoosedIndex])) {
      int size = dataPackage.nextInt();
      frmChooseAvatar.currentPageAvatarIds = StringArray.create(size);
      frmChooseAvatar.requestedAvatar = new boolean[size];
      for (int i = 0; i < size; i++) {
        frmChooseAvatar.currentPageAvatarIds.array[i] = dataPackage.nextString();
        frmChooseAvatar.requestedAvatar[i] = false;
      }
    }
  }
  
  public void onReceivedCategoryList(DataPackage dataPackage) {
    int size = dataPackage.nextInt();
    StringArray categories = StringArray.create(size);
    int[] numberOfAvatarByCategory = new int[size];
    for (int i = 0; i < size; i++) {
      categories.array[i] = dataPackage.nextString();
      numberOfAvatarByCategory[i] = dataPackage.nextInt();
    }
    FrmChooseAvatar frmChooseAvatar = (FrmChooseAvatar) FrmChooseAvatar.instance();
    frmChooseAvatar.setCategoryList(categories, numberOfAvatarByCategory);
  }
  
  public void onChangeAvatarSuccess(DataPackage dataPackage) {
    String avatarId = dataPackage.nextString();
    Global.currentUser.setAvatarId(avatarId);
    Global.alert.showAlert2(this, GameAlert.OK_TYPE, "Đổi avatar thành công", 99);
  }
  
  public void onChangeAvatarFail(DataPackage dataPackage) {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Đổi avatar thất bại");
  }
  
  public void onAvatarNotFounḍ(DataPackage dataPackage) {
    String avatarId = dataPackage.nextString();
    AvatarCache.putAvatar(avatarId, Global.getDefaultAvatar());
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 99) {
      Global.nextState(FrmUserInfo.instance(), null);
    }
  }
}
